package com.bank.ui.admin;

import com.bank.dao.*;
import com.bank.entity.*;
import com.bank.dao.CSVExporter;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.File;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class AdminDashboard extends JPanel {
    private static final Logger LOGGER = Logger.getLogger(AdminDashboard.class.getName());
    private final DepositTypeDAO depositTypeDAO = new DepositTypeDAO();
    private JTable depositTypeTable;
    private JTable customerTable;
    private JTable cardTable;
    private JTable transactionTable;

    public AdminDashboard() {
        setLayout(new BorderLayout());

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();

        // 添加各管理模块选项卡
        tabbedPane.addTab("客户管理", createCustomerManagementPanel());
        tabbedPane.addTab("银行卡管理", createCardManagementPanel());
        tabbedPane.addTab("存款业务管理", createDepositTypeManagementPanel());
        tabbedPane.addTab("交易管理", createTransactionManagementPanel());

        add(tabbedPane, BorderLayout.CENTER);
    }

    // 存款类型管理面板
    private JPanel createDepositTypeManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建表格模型（不可编辑）
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        model.addColumn("业务类型编号");
        model.addColumn("业务名称");
        model.addColumn("描述");

        // 初始化表格
        depositTypeTable = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(depositTypeTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

        // 增加存款业务按钮
        JButton addButton = new JButton("增加存款业务");
        addButton.addActionListener(e -> {
            AddDepositTypeDialog dialog = new AddDepositTypeDialog();
            dialog.setVisible(true);
            refreshDepositTypeTable();
        });

        // 修改存款业务按钮
        JButton editButton = new JButton("修改存款业务");
        editButton.addActionListener(e -> {
            int selectedRow = depositTypeTable.getSelectedRow();
            if (selectedRow >= 0) {
                int savingID = (int) depositTypeTable.getValueAt(selectedRow, 0);
                EditDepositTypeDialog dialog = new EditDepositTypeDialog(savingID);
                dialog.setVisible(true);
                refreshDepositTypeTable();
            } else {
                JOptionPane.showMessageDialog(panel,
                        "请选择要修改的存款业务",
                        "提示",
                        JOptionPane.WARNING_MESSAGE);
            }
        });

        // 删除存款业务按钮
        JButton deleteButton = new JButton("删除存款业务");
        deleteButton.addActionListener(e -> {
            int selectedRow = depositTypeTable.getSelectedRow();
            if (selectedRow >= 0) {
                int savingID = (int) depositTypeTable.getValueAt(selectedRow, 0);
                String savingName = (String) depositTypeTable.getValueAt(selectedRow, 1);

                int confirm = JOptionPane.showConfirmDialog(panel,
                        "确定要删除存款业务 '" + savingName + "' 吗?",
                        "确认删除",
                        JOptionPane.YES_NO_OPTION);

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        depositTypeDAO.deleteDepositType(savingID);
                        refreshDepositTypeTable();
                        JOptionPane.showMessageDialog(panel,
                                "存款业务已删除",
                                "成功",
                                JOptionPane.INFORMATION_MESSAGE);
                    } catch (SQLException ex) {
                        LOGGER.log(Level.SEVERE, "删除存款业务失败", ex);
                        JOptionPane.showMessageDialog(panel,
                                "删除存款业务失败: " + ex.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(panel,
                        "请选择要删除的存款业务",
                        "提示",
                        JOptionPane.WARNING_MESSAGE);
            }
        });

        // 查询存款业务按钮
        JButton queryButton = new JButton("查询存款业务");
        queryButton.addActionListener(e -> {
            GeneralQueryDialog dialog = new GeneralQueryDialog(new DepositTypeQueryHandler());
            dialog.setVisible(true);
        });

        // 导出存款业务数据按钮
        JButton exportButton = new JButton("导出数据");
        exportButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("导出存款业务数据");
            fileChooser.setSelectedFile(new File("存款业务数据.csv"));

            int userSelection = fileChooser.showSaveDialog(panel);
            if (userSelection == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    List<DepositType> depositTypes = depositTypeDAO.getAllDepositTypes();
                    CSVExporter.exportDepositTypesToCSV(depositTypes, file.getAbsolutePath());
                    JOptionPane.showMessageDialog(panel,
                            "数据已导出到: " + file.getAbsolutePath(),
                            "导出成功",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex) {
                    LOGGER.log(Level.SEVERE, "导出存款业务数据失败", ex);
                    JOptionPane.showMessageDialog(panel,
                            "导出失败: " + ex.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshDepositTypeTable());

        // 添加按钮到面板
        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(exportButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshDepositTypeTable();

        return panel;
    }

    // 存款类型表格刷新方法
    private void refreshDepositTypeTable() {
        DefaultTableModel model = (DefaultTableModel) depositTypeTable.getModel();
        model.setRowCount(0);

        try {
            List<DepositType> depositTypes = depositTypeDAO.getAllDepositTypes();

            for (DepositType type : depositTypes) {
                model.addRow(new Object[]{
                        type.getSavingID(),
                        type.getSavingName(),
                        type.getDescript()
                });
            }
        } catch (SQLException ex) {
            LOGGER.log(Level.SEVERE, "加载存款类型失败", ex);
            JOptionPane.showMessageDialog(this, "加载数据失败: " + ex.getMessage(),
                    "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private JPanel createCustomerManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        model.addColumn("客户编号");
        model.addColumn("客户姓名");
        model.addColumn("身份证号");
        model.addColumn("联系电话");
        model.addColumn("联系地址");

        // 初始化表格
        customerTable = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(customerTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

        // 增加客户按钮 - 修复后的监听器
        JButton addButton = new JButton("增加客户");
        addButton.addActionListener(e -> {
            new AddCustomerDialog(() -> refreshCustomerTable()).setVisible(true);
        });

        // 修改客户按钮 - 修复后的监听器
        JButton editButton = new JButton("修改客户");
        editButton.addActionListener(e -> {
            int selectedRow = customerTable.getSelectedRow();
            if (selectedRow != -1) {
                int customerID = (int) customerTable.getValueAt(selectedRow, 0);
                new EditCustomerDialog(customerID, () -> refreshCustomerTable()).setVisible(true);
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的客户！", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 删除客户按钮
        JButton deleteButton = new JButton("删除客户");
        deleteButton.addActionListener(e -> {
            int selectedRow = customerTable.getSelectedRow();
            if (selectedRow != -1) {
                int customerID = (int) customerTable.getValueAt(selectedRow, 0);
                int confirm = JOptionPane.showConfirmDialog(this, "确定要删除该客户吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        CustomerDAO dao = new CustomerDAO();
                        dao.deleteCustomer(customerID);
                        refreshCustomerTable();
                    } catch (SQLException ex) {
                        LOGGER.log(Level.SEVERE, "删除客户失败", ex);
                        JOptionPane.showMessageDialog(this, "删除客户失败！", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的客户！", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 查询客户按钮
        JButton queryButton = new JButton("查询客户");
        queryButton.addActionListener(e -> {
            GeneralQueryDialog dialog = new GeneralQueryDialog(new CustomerQueryHandler());
            dialog.setVisible(true);
        });

        // 导出客户数据按钮
        JButton exportButton = new JButton("导出客户数据");
        exportButton.addActionListener(e -> {
            try {
                CustomerDAO customerDAO = new CustomerDAO();
                List<Customer> customers = customerDAO.getAllCustomers();
                CSVExporter.exportUsersToCSV(customers, "customers.csv");
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "导出客户数据失败", ex);
                JOptionPane.showMessageDialog(this, "导出客户数据时发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshCustomerTable());

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(exportButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshCustomerTable();

        return panel;
    }
    private void refreshCustomerTable() {
        DefaultTableModel model = (DefaultTableModel) customerTable.getModel();
        model.setRowCount(0);

        try {
            CustomerDAO customerDAO = new CustomerDAO();
            List<Customer> customers = customerDAO.getAllCustomers();

            for (Customer customer : customers) {
                model.addRow(new Object[]{
                        customer.getCustomerID(),
                        customer.getCustomerName(),
                        customer.getPID(),
                        customer.getTelephone(),
                        customer.getAddress()
                });
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "加载客户数据失败", e);
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(),
                    "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // 银行卡管理面板
    private JPanel createCardManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        model.addColumn("卡号");
        model.addColumn("存款类型");
        model.addColumn("开户日期");
        model.addColumn("开户金额");
        model.addColumn("余额");
        model.addColumn("是否挂失");
        model.addColumn("客户编号");

        // 初始化表格
        cardTable = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(cardTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

        // 增加银行卡按钮
        JButton addButton = new JButton("增加银行卡");
        addButton.addActionListener(e -> {
            new AddCardDialog().setVisible(true);
            refreshCardTable();
        });

        // 修改银行卡按钮
        JButton editButton = new JButton("修改银行卡");
        editButton.addActionListener(e -> {
            int selectedRow = cardTable.getSelectedRow();
            if (selectedRow != -1) {
                String cardID = cardTable.getValueAt(selectedRow, 0).toString();
                new EditCardDialog(cardID).setVisible(true);
                refreshCardTable();
            } else {
                JOptionPane.showMessageDialog(this, "请选择要修改的银行卡！", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 删除银行卡按钮
        JButton deleteButton = new JButton("删除银行卡");
        deleteButton.addActionListener(e -> {
            int selectedRow = cardTable.getSelectedRow();
            if (selectedRow != -1) {
                String cardID = cardTable.getValueAt(selectedRow, 0).toString();
                int confirm = JOptionPane.showConfirmDialog(this, "确定要删除该银行卡吗？", "确认删除", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        CardDAO dao = new CardDAO();
                        dao.deleteCard(cardID);
                        refreshCardTable();
                    } catch (SQLException ex) {
                        LOGGER.log(Level.SEVERE, "删除银行卡失败", ex);
                        JOptionPane.showMessageDialog(this, "删除银行卡失败！", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } else {
                JOptionPane.showMessageDialog(this, "请选择要删除的银行卡！", "提示", JOptionPane.WARNING_MESSAGE);
            }
        });

        // 查询银行卡按钮
        JButton queryButton = new JButton("查询银行卡");
        queryButton.addActionListener(e -> {
            GeneralQueryDialog dialog = new GeneralQueryDialog(new CardQueryHandler());
            dialog.setVisible(true);
        });

        // 导出银行卡数据按钮
        JButton exportButton = new JButton("导出银行卡数据");
        exportButton.addActionListener(e -> {
            try {
                CardDAO cardDAO = new CardDAO();
                List<Card> cards = cardDAO.getAllCards();
                CSVExporter.exportCardsToCSV(cards, "cards.csv");
            } catch (Exception ex) {
                LOGGER.log(Level.SEVERE, "导出银行卡数据失败", ex);
                JOptionPane.showMessageDialog(this, "导出银行卡数据时发生错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshCardTable());

        buttonPanel.add(addButton);
        buttonPanel.add(editButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(queryButton);
        buttonPanel.add(exportButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshCardTable();

        return panel;
    }

    private void refreshCardTable() {
        DefaultTableModel model = (DefaultTableModel) cardTable.getModel();
        model.setRowCount(0);

        try {
            CardDAO cardDAO = new CardDAO();
            List<Card> cards = cardDAO.getAllCards();

            for (Card card : cards) {
                model.addRow(new Object[]{
                        card.getCardID(),
                        card.getSavingID(),
                        card.getOpenDate(),
                        card.getOpenMoney(),
                        card.getBalance(),
                        card.getIsReportLoss(),
                        card.getCustomerID()
                });
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "加载银行卡数据失败", e);
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(),
                    "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }


    // 交易管理面板
    private JPanel createTransactionManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建表格模型
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        model.addColumn("交易ID");
        model.addColumn("交易日期");
        model.addColumn("交易类型");
        model.addColumn("卡号");
        model.addColumn("交易金额");
        model.addColumn("备注");

        // 初始化表格
        transactionTable = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(transactionTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 0));

        // 查询交易按钮
        JButton queryButton = new JButton("查询交易");
        queryButton.addActionListener(e -> {
            GeneralQueryDialog dialog = new GeneralQueryDialog(new TransactionQueryHandler());
            dialog.setVisible(true);
        });

        // 修改交易按钮 (新增)
        JButton updateButton = new JButton("修改交易");
        updateButton.addActionListener(e -> {
            int selectedRow = transactionTable.getSelectedRow();
            if (selectedRow != -1) {
                int tradeID = (int) transactionTable.getValueAt(selectedRow, 0);
                String tradeType = (String) transactionTable.getValueAt(selectedRow, 2);
                String cardID = (String) transactionTable.getValueAt(selectedRow, 3);
                double currentAmount = (double) transactionTable.getValueAt(selectedRow, 4);
                String currentRemark = (String) transactionTable.getValueAt(selectedRow, 5);

                // 创建编辑对话框
                JDialog editDialog = new JDialog((Window) SwingUtilities.getWindowAncestor(this), "修改交易记录", Dialog.ModalityType.APPLICATION_MODAL);
                editDialog.setLayout(new BorderLayout());
                editDialog.setSize(400, 300);
                editDialog.setLocationRelativeTo(this);

                // 主内容面板
                JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
                mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

                // 信息面板 - 使用网格布局显示基本信息
                JPanel infoPanel = new JPanel(new GridLayout(0, 2, 10, 10));

                // 交易ID
                infoPanel.add(new JLabel("交易ID:"));
                JTextField idField = new JTextField(String.valueOf(tradeID));
                idField.setEditable(false);
                infoPanel.add(idField);

                // 交易类型
                infoPanel.add(new JLabel("交易类型:"));
                JTextField typeField = new JTextField(tradeType);
                typeField.setEditable(false);
                infoPanel.add(typeField);

                // 卡号
                infoPanel.add(new JLabel("卡号:"));
                JTextField cardField = new JTextField(cardID);
                cardField.setEditable(false);
                infoPanel.add(cardField);

                // 交易金额
                infoPanel.add(new JLabel("交易金额:"));
                JSpinner amountSpinner = new JSpinner(new SpinnerNumberModel(currentAmount, 0.01, 1000000, 0.01));
                infoPanel.add(amountSpinner);

                mainPanel.add(infoPanel, BorderLayout.NORTH);

                // 备注区域
                JPanel remarkPanel = new JPanel(new BorderLayout(5, 5));
                remarkPanel.add(new JLabel("备注:"), BorderLayout.NORTH);
                JTextArea remarkArea = new JTextArea(currentRemark, 3, 20);
                remarkArea.setLineWrap(true);
                remarkArea.setWrapStyleWord(true);
                JScrollPane remarkScroll = new JScrollPane(remarkArea);
                remarkPanel.add(remarkScroll, BorderLayout.CENTER);

                mainPanel.add(remarkPanel, BorderLayout.CENTER);

                editDialog.add(mainPanel, BorderLayout.CENTER);

                // 操作按钮面板
                JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
                JButton saveButton = new JButton("确认修改");
                JButton cancelButton = new JButton("取消");

                saveButton.addActionListener(ev -> {
                    double newAmount = (double) amountSpinner.getValue();
                    String newRemark = remarkArea.getText().trim();

                    if (newRemark.isEmpty()) {
                        JOptionPane.showMessageDialog(
                                editDialog,
                                "备注不能为空",
                                "输入错误",
                                JOptionPane.WARNING_MESSAGE
                        );
                        return;
                    }

                    try {
                        TransactionDAO dao = new TransactionDAO();
                        if (dao.updateTransaction(tradeID, newAmount, newRemark)) {
                            refreshTransactionTable();
                            editDialog.dispose();
                            JOptionPane.showMessageDialog(
                                    this,
                                    "交易记录更新成功",
                                    "操作成功",
                                    JOptionPane.INFORMATION_MESSAGE
                            );
                        }
                    } catch (SQLException ex) {
                        LOGGER.log(Level.SEVERE, "更新交易记录失败", ex);
                        String errorMsg = ex.getMessage();
                        if (errorMsg.contains("系统交易记录")) {
                            errorMsg = "系统交易记录（如转账）不能修改金额";
                        }
                        JOptionPane.showMessageDialog(
                                editDialog,
                                "更新失败: " + errorMsg,
                                "操作错误",
                                JOptionPane.ERROR_MESSAGE
                        );
                    }
                });

                cancelButton.addActionListener(ev -> editDialog.dispose());

                actionPanel.add(cancelButton);
                actionPanel.add(saveButton);

                editDialog.add(actionPanel, BorderLayout.SOUTH);

                // 设置对话框行为
                editDialog.getRootPane().setDefaultButton(saveButton);
                editDialog.pack();
                editDialog.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(
                        this,
                        "请选择要修改的交易记录！",
                        "操作提示",
                        JOptionPane.WARNING_MESSAGE
                );
            }
        });
        // 删除交易按钮
        JButton deleteButton = new JButton("删除交易");
        deleteButton.addActionListener(e -> {
            int selectedRow = transactionTable.getSelectedRow();
            if (selectedRow != -1) {
                int tradeID = (int) transactionTable.getValueAt(selectedRow, 0);
                String tradeInfo = String.format(
                        "交易ID: %d, 类型: %s, 金额: %.2f, 卡号: %s",
                        tradeID,
                        transactionTable.getValueAt(selectedRow, 2),
                        transactionTable.getValueAt(selectedRow, 4),
                        transactionTable.getValueAt(selectedRow, 3)
                );

                int confirm = JOptionPane.showConfirmDialog(
                        this,
                        "确定要删除该交易记录吗？\n" + tradeInfo,
                        "确认删除",
                        JOptionPane.YES_NO_OPTION
                );

                if (confirm == JOptionPane.YES_OPTION) {
                    try {
                        TransactionDAO dao = new TransactionDAO();
                        if (dao.deleteTransaction(tradeID)) {
                            refreshTransactionTable();
                            JOptionPane.showMessageDialog(
                                    this,
                                    "交易记录已删除",
                                    "成功",
                                    JOptionPane.INFORMATION_MESSAGE
                            );
                        }
                    } catch (SQLException ex) {
                        LOGGER.log(Level.SEVERE, "删除交易记录失败", ex);
                        String errorMsg = ex.getMessage();
                        if (errorMsg.contains("不支持此交易类型的删除操作")) {
                            errorMsg = "系统交易记录（如转账）不能删除";
                        }
                        JOptionPane.showMessageDialog(
                                this,
                                "删除失败: " + errorMsg,
                                "错误",
                                JOptionPane.ERROR_MESSAGE
                        );
                    }
                }
            } else {
                JOptionPane.showMessageDialog(
                        this,
                        "请选择要删除的交易记录！",
                        "提示",
                        JOptionPane.WARNING_MESSAGE
                );
            }
        });

        // 导出交易数据按钮
        JButton exportButton = new JButton("导出交易数据");
        exportButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("导出交易数据");
            fileChooser.setSelectedFile(new File("交易记录.csv"));

            int userSelection = fileChooser.showSaveDialog(panel);
            if (userSelection == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    TransactionDAO transactionDAO = new TransactionDAO();
                    List<Transaction> transactions = transactionDAO.getAllTransactions();
                    CSVExporter.exportTransactionsToCSV(transactions, file.getAbsolutePath());
                    JOptionPane.showMessageDialog(panel,
                            "数据已导出到: " + file.getAbsolutePath(),
                            "导出成功",
                            JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex) {
                    LOGGER.log(Level.SEVERE, "导出交易数据失败", ex);
                    JOptionPane.showMessageDialog(panel,
                            "导出失败: " + ex.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 刷新按钮
        JButton refreshButton = new JButton("刷新");
        refreshButton.addActionListener(e -> refreshTransactionTable());

        // 添加按钮到面板
        buttonPanel.add(queryButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(exportButton);
        buttonPanel.add(refreshButton);

        panel.add(buttonPanel, BorderLayout.SOUTH);

        // 初始加载数据
        refreshTransactionTable();

        return panel;
    }

    private void refreshTransactionTable() {
        DefaultTableModel model = (DefaultTableModel) transactionTable.getModel();
        model.setRowCount(0);

        try {
            TransactionDAO transactionDAO = new TransactionDAO();
            List<Transaction> transactions = transactionDAO.getAllTransactions();

            for (Transaction transaction : transactions) {
                model.addRow(new Object[]{
                        transaction.getTradeID(),
                        transaction.getTradeDate(),
                        transaction.getTradeType(),
                        transaction.getCardID(),
                        transaction.getTradeMoney(),
                        transaction.getRemark()
                });
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "加载交易数据失败", e);
            JOptionPane.showMessageDialog(this, "加载数据失败: " + e.getMessage(),
                    "数据库错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    // ================ 查询处理器实现 ================

    private class DepositTypeQueryHandler implements GeneralQueryDialog.QueryHandler {
        private final DepositTypeDAO dao = new DepositTypeDAO();


        @Override
        public String[] getQueryTypes() {

            return new String[]{"按名称模糊查询", "按ID范围查询", "按业务类型存款编号查询"};
        }

        @Override
        public List<Object> performQuery(String queryType, String queryText) throws SQLException {
            if ("按名称模糊查询".equals(queryType)) {
                return new ArrayList<>(dao.getDepositTypesByNameLike(queryText));
            } else if ("按ID范围查询".equals(queryType)) {
                String[] parts = queryText.split("-");
                if (parts.length != 2) {
                    throw new IllegalArgumentException("请输入正确的ID范围格式：起始ID-结束ID");
                }
                int startID = Integer.parseInt(parts[0]);
                int endID = Integer.parseInt(parts[1]);
                return new ArrayList<>(dao.getDepositTypesByIDRange(startID, endID));
            }
            // 新增：按业务类型编号查询
            else if ("按业务类型编号查询".equals(queryType)) {
                try {
                    int savingID = Integer.parseInt(queryText);
                    DepositType type = dao.getDepositTypeByID(savingID);
                    if (type != null) {
                        return Collections.singletonList(type);
                    } else {
                        return new ArrayList<>();
                    }
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("业务类型编号必须是整数");
                }
            }
            return new ArrayList<>();
        }

        @Override
        public String[] getColumnNames() {
            return new String[]{"业务类型编号", "业务名称", "描述"};
        }

        @Override
        public Object[] convertToTableRow(Object result) {
            DepositType type = (DepositType) result;
            return new Object[]{type.getSavingID(), type.getSavingName(), type.getDescript()};
        }
    }



    private class CustomerQueryHandler implements GeneralQueryDialog.QueryHandler {
        private final CustomerDAO dao = new CustomerDAO();

        @Override
        public String[] getQueryTypes() {
            return new String[]{"精确查询（身份证号）", "模糊查询（姓名）", "范围查询（客户编号）"};
        }

        @Override
        public List<Object> performQuery(String queryType, String queryText) throws SQLException {
            if ("精确查询（身份证号）".equals(queryType)) {
                Customer customer = dao.getCustomerByPID(queryText);
                return customer != null ? Collections.singletonList(customer) : new ArrayList<>();
            } else if ("模糊查询（姓名）".equals(queryType)) {
                return new ArrayList<>(dao.getCustomersByNameLike(queryText));
            } else if ("范围查询（客户编号）".equals(queryType)) {
                String[] range = queryText.split("-");
                int startID = Integer.parseInt(range[0]);
                int endID = Integer.parseInt(range[1]);
                return new ArrayList<>(dao.getCustomersByIDRange(startID, endID));
            }
            return new ArrayList<>();
        }

        @Override
        public String[] getColumnNames() {
            return new String[]{"客户编号", "客户姓名", "身份证号", "联系电话", "联系地址"};
        }

        @Override
        public Object[] convertToTableRow(Object result) {
            Customer customer = (Customer) result;
            return new Object[]{
                    customer.getCustomerID(),
                    customer.getCustomerName(),
                    customer.getPID(),
                    customer.getTelephone(),
                    customer.getAddress()
            };
        }
    }

    private class CardQueryHandler implements GeneralQueryDialog.QueryHandler {
        private final CardDAO dao = new CardDAO();

        @Override
        public String[] getQueryTypes() {
            return new String[]{"按卡号精确查询", "按客户ID查询", "按开户日期范围查询"};
        }

        @Override
        public List<Object> performQuery(String queryType, String queryText) throws SQLException {
            if ("按卡号精确查询".equals(queryType)) {
                Card card = dao.getCardByID(queryText);
                return card != null ? Collections.singletonList(card) : new ArrayList<>();
            } else if ("按客户ID查询".equals(queryType)) {
                int customerId = Integer.parseInt(queryText);
                return new ArrayList<>(dao.getCardsByCustomerId(customerId));
            } else if ("按开户日期范围查询".equals(queryType)) {
                String[] dates = queryText.split("至");
                if (dates.length != 2) {
                    throw new IllegalArgumentException("请输入正确的日期范围格式：YYYY-MM-DD至YYYY-MM-DD");
                }
                java.sql.Date startDate = java.sql.Date.valueOf(dates[0]);
                java.sql.Date endDate = java.sql.Date.valueOf(dates[1]);
                return new ArrayList<>(dao.getCardsByOpenDateRange(startDate, endDate));
            }
            return new ArrayList<>();
        }

        @Override
        public String[] getColumnNames() {
            return new String[]{"卡号", "存款类型", "开户日期", "开户金额", "余额", "是否挂失", "客户编号"};
        }

        @Override
        public Object[] convertToTableRow(Object result) {
            Card card = (Card) result;
            return new Object[]{
                    card.getCardID(),
                    card.getSavingID(),
                    card.getOpenDate(),
                    card.getOpenMoney(),
                    card.getBalance(),
                    card.getIsReportLoss(),
                    card.getCustomerID()
            };
        }
    }

    private class TransactionQueryHandler implements GeneralQueryDialog.QueryHandler {
        private final TransactionDAO dao = new TransactionDAO();
        private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public String[] getQueryTypes() {
            // 添加更多查询类型
            return new String[]{"按卡号查询", "按交易类型查询", "按日期范围查询", "多条件组合查询"};
        }

        @Override
        public List<Object> performQuery(String queryType, String queryText) throws SQLException {
            try {
                switch (queryType) {
                    case "按卡号查询":
                        return new ArrayList<>(dao.getTransactionsByCardID(queryText));

                    case "按交易类型查询":
                        return new ArrayList<>(dao.queryTransactionsByCriteria(null, queryText, null, null, null, null));

                    case "按日期范围查询":
                        String[] dates = queryText.split("至");
                        if (dates.length != 2) {
                            throw new IllegalArgumentException("请输入正确的日期范围格式：YYYY-MM-DD至YYYY-MM-DD");
                        }
                        Date start = sdf.parse(dates[0]);

                        // 结束日期设置为当天的23:59:59
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(sdf.parse(dates[1]));
                        cal.set(Calendar.HOUR_OF_DAY, 23);
                        cal.set(Calendar.MINUTE, 59);
                        cal.set(Calendar.SECOND, 59);
                        Date end = cal.getTime();

                        return new ArrayList<>(dao.getTransactionsByDateRange(start, end));

                    case "多条件组合查询":
                        // 解析复杂查询条件
                        Map<String, String> params = parseComplexQuery(queryText);
                        // 解析日期
                        Date startDate = null;
                        Date endDate = null;
                        if (params.containsKey("开始")) {
                            startDate = sdf.parse(params.get("开始"));
                        }
                        if (params.containsKey("结束")) {
                            Calendar calEnd = Calendar.getInstance();
                            calEnd.setTime(sdf.parse(params.get("结束")));
                            calEnd.set(Calendar.HOUR_OF_DAY, 23);
                            calEnd.set(Calendar.MINUTE, 59);
                            calEnd.set(Calendar.SECOND, 59);
                            endDate = calEnd.getTime();
                        }
                        Integer tradeId = null;
                        if (params.containsKey("ID")) {
                            tradeId = Integer.parseInt(params.get("ID"));
                        }
                        return new ArrayList<>(dao.queryTransactionsByCriteria(
                                params.get("卡号"),
                                params.get("类型"),
                                startDate,
                                endDate,
                                params.get("备注"),
                                tradeId
                        ));

                    default:
                        return new ArrayList<>(dao.getAllTransactions());
                }
            } catch (java.text.ParseException e) {
                throw new IllegalArgumentException("日期格式错误，请使用YYYY-MM-DD格式");
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("交易ID必须是整数");
            }
        }

        // 解析复杂查询条件的方法
        private Map<String, String> parseComplexQuery(String queryText) {
            Map<String, String> params = new HashMap<>();
            String[] pairs = queryText.split(",");
            for (String pair : pairs) {
                String[] kv = pair.split("=");
                if (kv.length == 2) {
                    params.put(kv[0].trim(), kv[1].trim());
                }
            }
            return params;
        }

        @Override
        public String[] getColumnNames() {
            return new String[]{"交易ID", "交易日期", "交易类型", "卡号", "交易金额", "备注"};
        }

        @Override
        public Object[] convertToTableRow(Object result) {
            Transaction transaction = (Transaction) result;
            return new Object[]{
                    transaction.getTradeID(),
                    transaction.getTradeDate(),
                    transaction.getTradeType(),
                    transaction.getCardID(),
                    transaction.getTradeMoney(),
                    transaction.getRemark()
            };
        }
    }}